package com.shadowlight.hero_story;

import com.shadowlight.hero_story.config.AllConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.Properties;

/**
 * @Description todo
 * @Author cz
 * @Date 2022/3/15
 */
@Slf4j
public final class MysqlSessionFactory {

    private static SqlSessionFactory sqlSessionFactory;

    private MysqlSessionFactory() {
    }

    public static void init() {

        try {
            InputStream ins = Resources.getResourceAsStream("MyBatisConfig.xml");

            Properties prop = new Properties();
            prop.setProperty("MYSQL_SERVER_HOST", AllConfig.MYSQL_SERVER_HOST);
            prop.setProperty("MYSQL_SERVER_PORT", String.valueOf(AllConfig.MYSQL_SERVER_PORT));
            prop.setProperty("MYSQL_DB", AllConfig.MYSQL_DB);
            prop.setProperty("MYSQL_USER", AllConfig.MYSQL_USER);
            prop.setProperty("MYSQL_PASSWORD", AllConfig.MYSQL_PASSWORD);

            sqlSessionFactory = new SqlSessionFactoryBuilder().build(ins, prop);

            //创建临时会话
            SqlSession tempSession = sqlSessionFactory.openSession();
            //测试数据库连接
            tempSession.getConnection().createStatement().execute("select -1");
            //关闭临时会话
            tempSession.close();

            log.info("连接数据库成功");
        } catch (Exception e) {
            log.error("读取mybatis配置出错:{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    public static SqlSession openSession() {
        if (sqlSessionFactory == null) throw new RuntimeException("selSessionFactory未初始化");
        return sqlSessionFactory.openSession(true);
    }
}
